<template>
  <div>
    <div ref="container" id="container"></div>
  </div>
</template>

<script>
import G6 from "@antv/g6";
import { mockData } from './mock/data.js'
import './custom/node.js'
import './custom/edge.js'

export default {
  name: '',
  data () {
    return {
      mock: mockData,
      graph: null
    };
  },
  methods: {
    initGraph () {
      const _this = this
      const container = this.$refs.container
      this.graph = new G6.TreeGraph({
        container: 'container',
        width: container.clientWidth,
        height: 600,
        animate: false,
        modes: {
          default: [
            'drag-canvas',
            'zoom-canvas',
            {
              type: 'collapse-expand',
              shouldBegin (e) {
                const model = e.item.get('model')
                const name = e.target.get('name')
                if (name.indexOf('root-left-btn') >= 0) { // 根节点左侧按钮
                  _this.changeItemVisible(model.children, 'left')
                } else if (name.indexOf('root-right-btn') >= 0) { // 根节点右侧按钮
                  _this.changeItemVisible(model.children, 'right')
                } else {
                  return true
                }
              }
            }
          ]
        },
        defaultNode: {
          type: 'treeNode'
        },
        defaultEdge: {
          type: 'smooth'
        },
        layout: {
          type: 'compactBox',
          direction: 'H',
          getId: function getId (d) {
            return d.id
          },
          getHeight: function getHeight () {
            return 16
          },
          getWidth: function getWidth () {
            return 200
          },
          getVGap: function getVGap () {
            return 20
          },
          getHGap: function getHGap () {
            return 50
          },
          getSide: function getSide (d) {
            return d.data.side
          }
        }
      })

      this.graph.data(this.mock)
      this.graph.render()

      this.graph.fitCenter()
    },
    // 改变元素显示/隐藏
    changeItemVisible (item, dir, visible) {
      if (dir) { // 这时是根元素子节点，需要判断方向
        item.forEach(n => {
          if (n.side === dir) {
            const v = this.graph.findById(n.id).isVisible()
            this.changeItemVisible(n, "", !v)
          }
        })
      } else {
        const node = this.graph.findById(item.id)
        if (node) {
          visible ? this.graph.showItem(node) : this.graph.hideItem(node)
        }
        if (item.children && item.children.length) {
          item.children.forEach(n => {
            this.changeItemVisible(n, "", visible)
          })
        }
      }
    }
  },
  created () {
  },
  mounted () {
    this.initGraph()
  }
};
</script>

<style scoped>

</style>
